<?php

namespace app\admin\controller\admin;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Loader;
use app\admin\model\CaAuthGroup;
use app\admin\model\CaAuthGroupAccess;

/**
 * 用户管理
 *
 * @icon fa fa-file-text-o
 */
class Account extends Backend
{
    /**
     * School模型对象
     */
    protected $searchFields = 'id,nick_name,phone,user_province';
    protected $model = null;
    protected $noNeedRight = ['cx_province_select','whitelist_del','whitelist_add','whitelist','sms_apply_list','sms_verify_success','sms_verify_fail','sms_verify','sms_content_editPost','sms_content_edit','sms_manage','set_black','month_province','look_data','get_goods','month_reg','user_clicks','login_clicks','user_logins','user_list_cj_city','user_list_citys','user_list_citys_daily','province_users','daily_views_province','daily_active_province','user_list_cj','cancel_vip'];
//    protected $noNeedLogin = ['update_user'];
    protected $isSuperAdmin = false;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\CaAdmin();
        //是否超级管理员
        $this->isSuperAdmin = $this->auth->isSuperAdmin();
      //  $user_type = DB::name('ca_admin')->field('type')->where(['id' => session('admin.id')])->find();
        $user_id = DB::name('ub_admin')->where(['id' => session('admin.id')])->value('user_id');
        $this->get_phone = DB::name('zd_user_auth')->where(['user_id' => $user_id])->value('get_phone');

       // $this->assign('type', $user_type['type']);


        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $groupList = collection(CaAuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();

            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
//            $ids=input("ids");
//            if (isset($ids)){
//                $result[13]='&nbsp;└ 院校组';
//            }
            $groupdata = $result;
        }
        $this->view->assign('groupdata', $groupdata);
        $this->assignconfig("admin", ['id' => $this->auth->id]);
    }

    /**
      * 渠道管理
     */
    public function index()
    {
        $group_id = $this->auth->getGroupIds()[0];
        $uid = getAllChildId($group_id);
        $this->searchFields = false;
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();



            $childrenGroupIds = $this->childrenGroupIds;
            $groupName = CaAuthGroup::where('id', 'in', $childrenGroupIds)
                ->column('id,name');
            $authGroupList = CaAuthGroupAccess::where('group_id', 'in', $childrenGroupIds)
                ->field('uid,group_id')
                ->select();
            $adminGroupName = [];
            foreach ($authGroupList as $k => $v) {
                if (isset($groupName[$v['group_id']])) {
                    $adminGroupName[$v['uid']][$v['group_id']] = $groupName[$v['group_id']];
                }
            }
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $adminGroupName[$this->auth->id][$n['id']] = $n['name'];
            }




            //$model = DB::name('ccc_admin_school');

            $where = [];
            $where_str = '';
            if($group_id >2){
                $where['id'] = ['in',$uid];
            }

            $province = input('get.province/d');
            $nickname = input('get.nickname/s');
            $charge_person = input('get.charge_person/d');
            //if ($province) $where_str = 'FIND_IN_SET("'.$province.'",province)';
            if ($province) $where['b.province_id'] = $province;
            if ($charge_person) $where['group_id'] = $charge_person;
            if ($nickname) $where['a.nickname'] = ['like','%'.$nickname.'%'];

            $count =$this->model
                ->alias('a')
                ->join('app_ca_auth_group_access ac','a.id=ac.uid','left')
                ->where("a.`status`='normal'")
                ->where($where)
                ->where($where_str)
                ->count();

            $list=$this->model
                ->alias('a')
                ->join('app_ca_auth_group_access ac','a.id=ac.uid','left')
                ->where("a.`status`='normal'")
                ->where($where)
                ->where($where_str)
                ->limit($offset,$limit)
                ->select();
            $sql = $this->model->getLastSql();
            foreach ($list as $k => &$v) {
                $groups = isset($adminGroupName[$v['id']]) ? $adminGroupName[$v['id']] : [];
                $v['groups'] = implode(',', array_keys($groups));
                $v['groups_text'] = implode(',', array_values($groups));
                $v['add_user_name'] =DB::name('ca_admin')->where(['id'=>$v['add_user']])->value('nickname');
            }

            $result = array("total" => $count, "rows" => $list,
                'get_phone' => $this->get_phone,'post' => input('get.'),
                'where'=>$where,'sql'=>$sql);

            return json($result);
        }

//        $my_school=DB::name('ccc_admin_school')
//            ->where('charge_person_admin_id='.$this->auth->id)
//            ->where('is_quit=0')
//            ->count();
//        $this->assign('my_school', $my_school);
//
//        $auth_group=DB::name('ccc_auth_group')
//            ->field('id,name')
//            ->where('pid=7')
//            ->count();
//        $this->assign('auth_group', $auth_group);
//
//        $cooperation_school=DB::name('ccc_admin_school')
//            ->where('is_cooperation=1')
//            ->where('charge_person_admin_id='.$this->auth->id)
//            ->where('is_quit=0')
//            ->count();
//        $this->assign('cooperation_school', $cooperation_school);

        $charge_person=DB::name('ca_auth_group')
            ->alias('a')
            ->where("a.id>1 and a.`status`='normal'")
            ->select();
        $this->assign('charge_person', $charge_person);
        $this->assign('province', get_pro());
        $this->assign('m_id', $this->auth->id);
        return $this->view->fetch();
    }
    public function add(){
        //echo 123;
        $data=input('');
        $ids=isset($data['ids'])?$data['ids']:'';
        $s_name=isset($data['s_name'])?$data['s_name']:'';
        $type=isset($data['type'])?$data['type']:'';
        $this->assign('data',$data);

        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {

                $params['add_user']=session('admin.id');


                $id = $this->model->where(['username'=>$params['username']])->value('id');
                if($id){
                    $this->error('该手机号账号已存在');
                }
                $result = $this->model->save($params);

                if ($result === false) {
                    $this->error($this->model->getError());
                }
                $group = $this->request->post("group/a");
                $group = array_intersect($this->childrenGroupIds, $group);

                //过滤不允许的组别,避免越权
                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
                }
                model('CaAuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }

        if ($ids){
            $groupids = [];
            $this->view->assign("groupids", $groupids);
        }
        $pro=get_pro();
        $this->view->assign("pro", $pro);
        $this->view->assign("ids", $ids);
        $this->view->assign("type", $type);
        $this->view->assign("s_name", $s_name);
        return $this->view->fetch();

    }

    public function edit($ids = NULL){
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (!in_array($row->id, $this->childrenAdminIds)) {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
//                if ($params['password']) {
//                    if (!Validate::is($params['password'], '\S{6,16}')) {
//                        $this->error(__("Please input correct password"));
//                    }
//                    $params['salt'] = Random::alnum();
//                    $params['password'] = md5(md5($params['password']) . $params['salt']);
//                } else {
//                    unset($params['password'], $params['salt']);
//                }
//                $params['province']=join(",",$params['province']);

                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('CaAdmin');
                $adminValidate->rule([
                    'username' => 'require|unique:admin,username,' . $row->id,
//                    'email'    => 'require|email|unique:admin,email,' . $row->id,
                    'password' => 'regex:\S{32}',
                ]);
                $result = $row->validate('CaAdmin.edit')->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }

                // 先移除所有权限
                model('CaAuthGroupAccess')->where('uid', $row->id)->delete();

                $group = $this->request->post("group/a");

                // 过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);

                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $row->id, 'group_id' => $value];
                }
                model('CaAuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
        $grouplist = $this->auth->getGroups($row['id']);
        $groupids = [];
        foreach ($grouplist as $k => $v) {
            $groupids[] = $v['id'];
        }
        $this->view->assign("ids", $ids);
        $this->view->assign("row", $row);
        $pro=get_pro();
        $this->view->assign("pro", $pro);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }

    /**
     * 关闭
     * @return string|\think\response\Json
     */
    public function close($ids=null){  //审核
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $update['status'] = 'hidden';
        $update['updatetime'] = time();
        $result = $this->model->where(['id'=>$ids])->update($update);
        if($result){
            $this->success();
        }
        $this->error();
    }
    /**
     * open
     * @return string|\think\response\Json
     */
    public function open($ids=null){  //审核
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $update['status'] = 'normal';
        $update['updatetime'] = time();
        $result = $this->model->where(['id'=>$ids])->update($update);
        if($result){
            $this->success();
        }
        $this->error();
    }


    public function transfer(){

        if ($this->request->isPost()) {
            $user1 = $this->request->post("user1/d");//移交人
            $user2 = $this->request->post("user2/d");//接收人

            Db::name('card_put_info')
                ->where(['admin_id'=>$user1])
                ->update(['admin_id'=>$user2,'update_time'=>time()]);
            Db::name('card_log')->where(['admin_id' => $user1])->update(['admin_id' => $user2]);
            $data['user_from']=$user1;
            $data['user_to']=$user2;
            $data['admin_id'] = session('admin.id');
            $data['create_time']=time();
            Db::name('ca_admin_transfer')->insert($data);
        }
        $group_id = $this->auth->getGroupIds()[0];
        $uid = getAllChildId($group_id);
        $new_where = [];
        if($group_id>2){
            $new_where = [
                'id'=>['in',$uid]
            ];
        }
        $user = DB::name('ca_admin')
            ->field('id,nickname')
            ->where("`status`='normal'")
            ->where($new_where)
            ->select();
        $this->assign("user", $user);
        return $this->view->fetch();
    }

}
